import 'dart:io';

import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart';
import 'package:xws/utils/log_util.dart';

/// 本地存储相关
class _S {
  const _S._();
  static late Box<dynamic> _appBox;
  static bool _isInit = false;

  /// 初始化
  static Future<void> _init() async {
    try {
      if (_isInit) return;

      Hive.init(await getLocalPath('hive', isTemp: false));
      _appBox = await Hive.openBox<dynamic>('appBox');

      _isInit = true;
    } catch (e) {
      error('init hive box error $e');
    }
  }

  /// 抓取值
  static T? _getV<T extends Object>(dynamic key) {
    try {
      return _appBox.get(key) as T?;
    } catch (e) {
      error('get value error $e');
    }
  }

  /// 存储值
  static void _setV(dynamic key, dynamic value) {
    try {
      _appBox.put(key, value);
    } catch (e) {
      error('save value error $e');
    }
  }

  /// 获取全部值
  static Iterable<dynamic>? _getAllValue() {
    try {
      return _appBox.values;
    } catch (e) {
      error('get all values error $e');
      return null;
    }
  }

  /// 清空
  static Future<int> _clear() async {
    try {
      return await _appBox.clear();
    } catch (e) {
      error('clear hive error $e');
    }

    return 0;
  }
}

/// 获取app本地存储路径
/// * `folder` 保存的文件夹
/// * `isTemp` 是否为缓存
/// 返回'/folder/'
Future<String> getLocalPath(String folder, {bool isTemp = true}) async {
  final Directory _dir = isTemp ? await getTemporaryDirectory() : await getApplicationDocumentsDirectory();

  ///创建目录
  final Directory t = Directory(_dir.absolute.path + '/$folder');
  if (!t.existsSync()) {
    await t.create();
  }

  return _dir.absolute.path + '/$folder/';
}

/// 初始化hive库
Future<void> initHive() async => await _S._init();

/// 从hive库中读取值
T? getV<T extends Object>(dynamic key) => _S._getV<T>(key);

/// 将值存入hive库
void setV<T extends Object>(dynamic key, dynamic value) => _S._setV(key, value);

/// 读取hive全部数据
Iterable<dynamic>? getAll() => _S._getAllValue();

/// 清空hive库
Future<int> clearHive() async => await _S._clear();
